#!/bin/sh
git --version
git config --global http.schannelCheckRevoke false
git config --global http.sslBackend openssl

# usage: git_clone.sh $repo_url $branch $local_dir

LMS_GIT_REPO_URL="$1"
LMS_GIT_REPO_BRANCH="$2"
LMS_LOCAL_REPO_PATH="$3"
LMS_GIT_DEPTH_PARAM="--depth=1"

git_output=""

echo "git_clone_and_fetch: $LMS_GIT_REPO_URL, branch: $LMS_GIT_REPO_BRANCH, local dir: $LMS_LOCAL_REPO_PATH"

remove_lock_files () {
  # echo "It's a git repo"
  if [ -f "$LMS_LOCAL_REPO_PATH/.git/shallow.lock" ]; then
    echo "shallow.lock found. delete it."
    rm -f "$LMS_LOCAL_REPO_PATH/.git/shallow.lock"
  # else
  #   echo "no shallow.lock"
  fi

  if [ -f "$LMS_LOCAL_REPO_PATH/.git/index.lock" ]; then
    echo "index.lock found. delete it."
    rm -f "$LMS_LOCAL_REPO_PATH/.git/index.lock"
  # else
  #   echo "no index.lock"
  fi
}

clone_main_repo() {
  # echo "call clone_main_repo"
  git config --global --add safe.directory "$LMS_LOCAL_REPO_PATH"
  if [ -d "$LMS_LOCAL_REPO_PATH/.git" ]; then
    echo "It's a git repo. Only fetch."
  else
    git clone $LMS_GIT_REPO_URL "$LMS_LOCAL_REPO_PATH" $LMS_GIT_DEPTH_PARAM
  fi
  cd "$LMS_LOCAL_REPO_PATH"
  echo "git fetch new files"
  
  git_output=$(git fetch origin $LMS_GIT_REPO_BRANCH $LMS_GIT_DEPTH_PARAM && git reset --hard "origin/$LMS_GIT_REPO_BRANCH" 2>&1)
}

remove_git_dir() {
  if [ -d "$LMS_LOCAL_REPO_PATH/.git" ]; then
    echo "remove .git dir"
    rm -rf "$LMS_LOCAL_REPO_PATH/.git"
    git init
  fi
}

check_result_and_retry() {
  if [ $exit_code -ne 0 ] || echo "$git_output" | grep -q "error: non-monotonic" ; then
    cd "${LOCAL_REPO_PATH}"
    remove_git_dir
    if [ -d "$LOCAL_REPO_PATH/.git" ]; then
      echo "It's a git repo"
      remove_lock_files
    else
      echo "no .git dir"
      git init
    fi
    
    git remote -v
    git remote remove origin
    echo "change git remote url"
    git remote add origin $LMS_GIT_REPO_URL
    git remote -v
    echo "retry clone code"
    clone_main_repo
  fi
}

remove_lock_files

clone_main_repo

exit_code=$?
echo "git clone result: $exit_code"
echo "git clone git_output: $git_output"
check_result_and_retry


exit_code=$?
echo "git clone final result: $exit_code"
echo "git clone git_output: $git_output"
check_result_and_retry
